package com.adu.servlets;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;


/**
 * Servlet implementation class UploadServlet
 * 需要commons-fileupload-1.3.1.jar + commons-io-2.2.jar
 */
@WebServlet("/UploadServlet")
public class UploadServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doPost(request, response);
	}
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("utf-8");
		response.setCharacterEncoding("utf-8");
		response.setContentType("text/html;charset=utf-8");
		//创建文件项工厂
		DiskFileItemFactory factory = new DiskFileItemFactory();
		//保存路径
		String path = request.getServletContext().getRealPath("/WEB-INF/upload");
		File folder = new File(path);
		if(!folder.exists()||!folder.isDirectory()){
			folder.mkdir();
		}
		//设置文件仓库
		factory.setRepository(folder);
		//设置保存临时文件临界值
		factory.setSizeThreshold(1024*1024);
		//创建文件上传对象
		ServletFileUpload upload = new ServletFileUpload(factory);
		String fileName = "";
		try {
			//从请求中解析出文件项列表
			List<FileItem> list = (List<FileItem>)upload.parseRequest(request);
			for(FileItem item:list){
				//如果获取的是普通的文本信息
				if(item.isFormField()){
					//如果经过压缩，文件名会丢失变成blob,所以要获取客户端传来的文件名
					if("fileName".equals(item.getFieldName())){
						fileName = item.getString("utf-8");//解决中文乱码
					}
				}else{
					//如果文件在客户端未被压缩，则从item中获得文件名
					if(!"blob".equals(item.getName())){
						fileName = item.getName();
					}
					//创建文件输出流
					OutputStream out= new FileOutputStream(new File(path,fileName));
					//获取文件输入流，用于读取上传的文件
					InputStream in = item.getInputStream();
					int len = 0;
					byte[] buff = new byte[1024];
					System.out.println("获取上传文件的总容量："+item.getSize());
					while((len=in.read(buff))!=-1){
						out.write(buff, 0, len);
					}
					out.close();
					in.close();
				}
			}
		} catch (FileUploadException e) {
			e.printStackTrace();
		}
		
	}

}
